import { ref } from 'vue'
import { createSparePartApply, createSparePartApplyCheckStock } from '@/api/store'

/**
 * 配件申请单表单服务
 */
export const useSparePartApplyForm = () => {
  const formSaveLoading = ref(false)
  const form = ref<StorageAPIRequest.SparePartApplyForm>({
    area: '',
    city: '',
    province: '',
    town: '',
    code: '',
    contactName: '',
    contactPhone: '',
    createType: 1,
    detailAddress: '',
    id: '',
    materialApplyParamList: [],
    networkId: '',
    orderRemark: '',
    receivingStoreId: '',
    attachmentParamList: [],
    shippingStoreId: '',
    status: 1,
    type: 1,
  })

  const resetForm = () => {
    form.value = {
      area: '',
      city: '',
      province: '',
      town: '',
      code: '',
      contactName: '',
      contactPhone: '',
      createType: 1,
      detailAddress: '',
      id: '',
      materialApplyParamList: [],
      attachmentParamList: [],
      networkId: '',
      orderRemark: '',
      receivingStoreId: '',
      shippingStoreId: '',
      status: 1,
      type: 1,
    }
  }

  const submit = async () => {
    try {
      formSaveLoading.value = true
      const res = await createSparePartApply(form.value)
      formSaveLoading.value = false
      return res.data
    } catch (e) {
      formSaveLoading.value = false
    }
  }

  return {
    form,
    formSaveLoading,
    submit,
    resetForm,
  }
}

/**
 * 配件申请单提交时库存校验服务
 */
export const useCreateSparePartApplyCheckStockService = () => {
  const stockCheckLoading = ref(false)
  const stockCheckForm = ref<{ networkId: string; materialQty: Record<string, number> }>({
    networkId: '',
    materialQty: {},
  })
  const stockCheckResult = ref<{ isSufficient: 0 | 1; type: 1 | 2 | 3; difference: string }>({
    isSufficient: 1,
    type: 1,
    difference: '',
  })

  const stockCheck = async () => {
    try {
      stockCheckLoading.value = true
      const res = await createSparePartApplyCheckStock(stockCheckForm.value)
      stockCheckLoading.value = false
      if (res.data.code === 20000) {
        stockCheckResult.value = res.data.data.row
        return ''
      }

      return res.data.message
    } catch (e) {
      stockCheckLoading.value = false
    }
  }

  return {
    stockCheckForm,
    stockCheckResult,
    stockCheckLoading,
    stockCheck,
  }
}
